package com.snail.snailvr.views;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;

import com.snail.snailvr.R;
import com.snail.snailvr.VRApp;
import com.snail.snailvr.event.BusProvider;
import com.snail.snailvr.model.ActionItem;
import com.snail.snailvr.model.BaseData;
import com.snail.snailvr.model.NavDrawerItem;
import com.snail.snailvr.model.Tag;
import com.snail.snailvr.model.UpdateModel;
import com.snail.snailvr.model.VideoInfo;
import com.snail.snailvr.mvp.presenter.VersionUpdatePresenter;
import com.snail.snailvr.mvp.views.VersionUpdateView;
import com.snail.snailvr.network.providers.downloads.DownloadService;
import com.snail.snailvr.utils.AppUtils;
import com.snail.snailvr.utils.Constant;
import com.snail.snailvr.utils.DatabaseUtils;
import com.snail.snailvr.utils.DialogUtils;
import com.snail.snailvr.utils.IntentUtils;
import com.snail.snailvr.utils.LockUtil;
import com.snail.snailvr.utils.NetworkUtil;
import com.snail.snailvr.utils.PushInfoUtil;
import com.snail.snailvr.utils.SharedPreferencesUtil;
import com.snail.snailvr.utils.ToastUtils;
import com.snail.snailvr.views.adapter.HomePageAdapter;
import com.snail.snailvr.views.adapter.NavigationAdapter;
import com.snail.snailvr.views.fragments.DiscoverFragment;
import com.snail.snailvr.views.fragments.HomeFragment;
import com.snail.snailvr.views.fragments.InputFragment;
import com.snail.snailvr.widget.MenuPopup;
import com.squareup.otto.Subscribe;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import rx.Subscription;

import static com.snail.snailvr.utils.CDNConstant.APP_ID;
import static com.snail.snailvr.utils.CDNConstant.APP_VERSION;
import static com.snail.snailvr.utils.CDNConstant.PHONE_MODEL;
import static com.snail.snailvr.utils.CDNConstant.SYS_VERSION;
import static com.snail.snailvr.utils.CDNConstant.UUID;

public class MainActivity extends BaseActivity implements Toolbar.OnMenuItemClickListener, ViewPager.OnPageChangeListener, VersionUpdateView {

    public static Intent newIntent(Context context, int flags) {
        Intent intent = new Intent(context, MainActivity.class);
        intent.setFlags(flags);
        return intent;
    }
    private static final int MENU_SCAN = 0;
    private static final int MENU_LINK = 1;
    private static final int MENU_HISTORY = 2;
    @Bind(R.id.viewpager)
    ViewPager viewPager;
    @Bind(R.id.tabs)
    TabLayout tabLayout;
    @Bind(R.id.toolbar)
    Toolbar mToolbar;
    @Bind(R.id.drawer_layout)
    DrawerLayout mDrawerLayout;
    @Bind(R.id.nav_view)
    ListView mNavgationView;
    private View mLocalTabView;

    private String tabTitles[];
    private HomePageAdapter mHomePageAdapter;
    private NavigationAdapter mNavigationAdapter;
    private Subscription initNetDiskSubscription;
    private int dotCount;//新视频小蓝点

    private VersionUpdatePresenter presenter;
    private MenuPopup mMenuPopup;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        pushInfo();
        BusProvider.getInstance().register(this);
        checkUpdate();
        gestureVerify();
    }

    private void checkUpdate() {
        // 自动执行版本更新检测
        presenter = new VersionUpdatePresenter(this, mDrawerLayout);
        presenter.loadData(false);
    }

    private void gestureVerify() {
        int[] index = LockUtil.getPwd(this);
        // 判断当前是否设置了密码
        boolean hasPsw = index.length >= Constant.PATTERN_PSW_MIN_LENGTH ? true : false;
        if (hasPsw) {
            Intent intent = GestureUnlockActivity.getIntent(this, false);
            startActivity(intent);
        }
    }

    @Override
    protected void handleIntent() {

    }

    @Override
    protected void onNewIntent(Intent intent) {

    }

    @Override
    protected void initView() {
        initNetDiskInfo();
        setupViewPager(viewPager);
        setupTabLayout(tabLayout);
        setupToolbar();
        setUpDrawer();
        setUpNavigationView();
        startDownloadService();
        initPopWindow();
    }

    private void initPopWindow() {

        mMenuPopup = new MenuPopup(this);
        mMenuPopup.setItemOnClickListener(mOnItemOnClickListener);

        mMenuPopup.addAction(new ActionItem(this, getString(R.string.menu_scan), R.drawable.ic_menu_scan));
        mMenuPopup.addAction(new ActionItem(this, getString(R.string.menu_link), R.drawable.ic_menu_link));
        mMenuPopup.addAction(new ActionItem(this, getString(R.string.menu_history), R.drawable.ic_menu_history));
    }

    private void setUpNavigationView() {
        DrawerLayout.LayoutParams params = (DrawerLayout.LayoutParams) mNavgationView.getLayoutParams();
        if (params != null)
            params.width = getResources().getDisplayMetrics().widthPixels - getResources().getDimensionPixelSize(R.dimen.toolbar_height);

        View headerView = LayoutInflater.from(this).inflate(R.layout.nav_header, mNavgationView, false);
        mNavgationView.addHeaderView(headerView);

        mNavigationAdapter = new NavigationAdapter(this, getNavDrawerItems());
        mNavgationView.setAdapter(mNavigationAdapter);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == Constant.GESTURE_CODE) {
            mNavigationAdapter.notifyDataSetChanged();
        }

    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_main;
    }

    private void setUpDrawer() {
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, mDrawerLayout, mToolbar, R.string.navigation_drawer_open,
                R.string.navigation_drawer_close);
        toggle.setToolbarNavigationClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
                    closeDrawer();
                } else {
                    openDrawer();
                }
            }
        });
        mDrawerLayout.addDrawerListener(toggle);
        toggle.setHomeAsUpIndicator(R.drawable.ic_setting);
        toggle.setDrawerIndicatorEnabled(false);
        toggle.syncState();
    }

    private void setupToolbar() {
        tabTitles = getResources().getStringArray(R.array.tab_titles);
        mToolbar.inflateMenu(R.menu.menu_main);
        mToolbar.setTitle(tabTitles[HomePageAdapter.TAB_LOCAL]);
        mToolbar.setTitleTextColor(ContextCompat.getColor(this, R.color.toolbar_title_color));
        mToolbar.setOnMenuItemClickListener(this);
    }

    private void setupViewPager(ViewPager viewPager) {
        mHomePageAdapter = new HomePageAdapter(this, getSupportFragmentManager());
        mHomePageAdapter.addFragment(new HomeFragment(), R.drawable.drawable_tab_local);
        mHomePageAdapter.addFragment(new DiscoverFragment(), R.drawable.drawable_tab_web);

        mHomePageAdapter.addFragment(new InputFragment(), R.drawable.drawable_tab_input);
        viewPager.setAdapter(mHomePageAdapter);
        viewPager.setOffscreenPageLimit(2);
        viewPager.addOnPageChangeListener(this);
    }

    public void setupTabLayout(TabLayout tabLayout) {
        tabLayout.setSelectedTabIndicatorColor(ContextCompat.getColor(this, R.color.tab_indicator_color));
        tabLayout.setTabMode(TabLayout.MODE_FIXED);
        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
        tabLayout.setupWithViewPager(viewPager);
        for (int i = 0; i < tabLayout.getTabCount(); i++) {
            TabLayout.Tab tab = tabLayout.getTabAt(i);
            if (tab != null) {
                tab.setCustomView(mHomePageAdapter.getTabView(i));
                if (i == 0)
                    mLocalTabView = tab.getCustomView();
            }
        }
        tabLayout.requestFocus();
    }


    /**
     * 添加视频下载
     *
     * @param videoInfo
     */
    @Subscribe
    public void addNewTask(VideoInfo videoInfo) {
        if (videoInfo != null && !videoInfo.isDemoVideo()) {
            if (viewPager.getCurrentItem() != HomePageAdapter.TAB_LOCAL) {
                ++dotCount;
                showNewdot();
            }
        }
    }

    /**
     * 当有新视频下载完成显示蓝色小圆点
     */
    private void showNewdot() {
        if (mLocalTabView != null) {
            TextView dot = (TextView) mLocalTabView.findViewById(R.id.dot);
            dot.setVisibility(dotCount == 0 ? View.GONE : View.VISIBLE);
            if (dotCount > 0 && dotCount < 10)
                dot.setText(String.valueOf(dotCount));

        }
    }

    private void hideNewDot() {
        dotCount = 0;
        showNewdot();
    }

    /**
     * 启动下载服务
     * 当判断Wifi开启时，启动服务
     */
    private void startDownloadService() {
        //判断当前网络是否可用，网络可用标准，1.链接 2.可用 3.wifi状态
        if (NetworkUtil.isWifiConnected()) {
            // 当链接为wifi状态时运行开启DownloadService
            DownloadService.start(this);
        }
    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_option:
                mMenuPopup.show(mToolbar);
                return true;
        }
        return false;
    }

    private void openDrawer() {
        mDrawerLayout.openDrawer(GravityCompat.START);
    }

    private void closeDrawer() {
        mDrawerLayout.closeDrawer(GravityCompat.START);
    }

    @Override
    public void onBackPressed() {
        if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
            mDrawerLayout.closeDrawer(GravityCompat.START);
        } else if (viewPager.getCurrentItem() != HomePageAdapter.TAB_LOCAL) {
            viewPager.setCurrentItem(HomePageAdapter.TAB_LOCAL);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        mToolbar.setTitle(tabTitles[position]);
        if (position == HomePageAdapter.TAB_LOCAL)
            hideNewDot();
    }

    @Override
    public void onPageScrollStateChanged(int state) {
    }

    private List<NavDrawerItem> getNavDrawerItems() {
        List<NavDrawerItem> navDrawerItems = new ArrayList<>(NavigationAdapter.NAV_COUNT);

        //upgrade
        NavDrawerItem item = new NavDrawerItem(getString(R.string.upgrade), null, R.drawable.ic_upgrade, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                presenter.loadData(true);
            }
        });
        navDrawerItems.add(item);
        //wifi only
        /*item = new NavDrawerItem(getString(R.string.wifi_only), null, R.drawable.ic_setting_wifi, false, true, null);
        navDrawerItems.add(item);*/
        //pattern
        item = new NavDrawerItem(getString(R.string.pattern), null, R.drawable.ic_setting_gesture, false, true, null);
        navDrawerItems.add(item);
        //feedback
        item = new NavDrawerItem(getString(R.string.feedback), null, R.drawable.ic_feedback, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                IntentUtils.feedBack(MainActivity.this);
            }
        });
        navDrawerItems.add(item);

        // 新增“关于”
        item = new NavDrawerItem(getString(R.string.about), null, R.drawable.ic_setting_about, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = AboutActivity.getIntent(MainActivity.this);
                startActivity(intent);
            }
        });
        navDrawerItems.add(item);

        return navDrawerItems;
    }

    private String getCacheSize() {
        return "3M";
    }


    /**
     * 初始化网盘信息
     */
    private void initNetDiskInfo() {
        if (SharedPreferencesUtil.getInstance(this).getIsFirst()) {
            initNetDiskSubscription = DatabaseUtils.initNetDiskInfo(this);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        PushInfoUtil.getInstance().unInit();
        if (initNetDiskSubscription != null && !initNetDiskSubscription.isUnsubscribed())
            initNetDiskSubscription.unsubscribe();
        DatabaseUtils.clearConnectPcList();
        BusProvider.getInstance().unregister(this);
        IntentUtils.stopWifiTransferServer(this);

        presenter.destroy();
        VRApp.getRequestQueue().cancelAll(Tag.TAG_VERSION_UPDATE);
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    public void showLoading() {
    }

    @Override
    public void hideLoading() {
    }

    @Override
    public void showEmpty() {
    }

    @Override
    public void showError() {

    }

    @Override
    public void onRequestComplete(BaseData data) {

    }

    @Override
    public void onRequestComplete(BaseData data, boolean isShowToast) {
        if (data instanceof UpdateModel) {
            UpdateModel versionUpdateModel = ((UpdateModel) data);
            if (versionUpdateModel != null && versionUpdateModel.getbUpdate()) {
                showUpdateDialog(versionUpdateModel);
            } else {
                if (isShowToast) {
                    ToastUtils.makeToastColorShow(this, mDrawerLayout, getResources().getString(R.string.no_update));
                }
                updateNavigationAdapterNoUpdate();
            }
        }
    }

    private void showUpdateDialog(UpdateModel versionUpdateModel) {

        startActivity(UpdateDialogActivity.newIntent(MainActivity.this, true
                , versionUpdateModel.getcApkUrl()
                , versionUpdateModel.getsDesc(), Intent.FLAG_ACTIVITY_NEW_TASK
                , versionUpdateModel.getcForceUpdate().equals(Constant.FORCE_UPDATE)));

        updateNavigationAdapter(versionUpdateModel.getcVersion());
    }

    private void updateNavigationAdapter(String version_name) {
        NavDrawerItem item = mNavigationAdapter.getItem(NavigationAdapter.NAV_UPGRADE);
        if (item != null) {
            item.setSub_title(getString(R.string.version, version_name));
            item.setIsShowDrawable(true);
            mNavigationAdapter.notifyDataSetChanged();
        }
    }

    private void updateNavigationAdapterNoUpdate() {
        NavDrawerItem item = mNavigationAdapter.getItem(NavigationAdapter.NAV_UPGRADE);
        if (item != null) {
            item.setSub_title(getResources().getString(R.string.no_update));
            item.setIsShowDrawable(false);
            mNavigationAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public Activity getContext() {
        return this;
    }


    private MenuPopup.OnItemOnClickListener mOnItemOnClickListener = new MenuPopup.OnItemOnClickListener() {

        @Override
        public void onItemClick(ActionItem item, int position) {

            switch (position) {
                case MENU_SCAN:
                    //new IntentIntegrator(MainActivity.this).setOrientationLocked(false).setCaptureActivity(ScannerActivity.class).initiateScan();
                    MainActivity.this.startActivity(new Intent(MainActivity.this,ScannerActivity.class));
                    break;
                case MENU_LINK:
                    showInputLiveAddressDialog();
                    break;
                case MENU_HISTORY:
                    IntentUtils.startHistoryActivity(MainActivity.this);
                    break;
            }

        }
    };

    private void showInputLiveAddressDialog() {
        DialogUtils.showInputDialog(MainActivity.this, true, getString(R.string.input_via_link), getString(R.string.enter_live_url), getString(R.string.hint_live_url), getString(R.string.CANCEL), getString(R.string.join), false, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Object tag = v.getTag();
                if (tag != null) {
                    final String url = (String) tag;

                    if(DialogUtils.showJudgeNetDialog(MainActivity.this,new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            IntentUtils.playVideo(MainActivity.this, url, "");
                        }
                    }))
                        return;
                    IntentUtils.playVideo(MainActivity.this, url, "");

                }
            }
        });
    }

    private void pushInfo() {
        Map<String,String> infoMap = new HashMap<>();
        infoMap.put(UUID, AppUtils.getIMEI(this));
        infoMap.put(PHONE_MODEL,AppUtils.getInfo());
        infoMap.put(SYS_VERSION,AppUtils.getVersionRelease());
        infoMap.put(APP_ID,"oxplayer_android");
        infoMap.put(APP_VERSION,AppUtils.getVersionName(this));
        PushInfoUtil.getInstance().pushInfo(infoMap);
    }
}
